package com.hsxc.cdz.controller.consoleController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsxc.cdz.base.bean.ConsoleUser;
import com.hsxc.cdz.base.util.Constants;
import com.hsxc.cdz.mgmt.user.UserManager;

import net.sf.json.JSONObject;

/**
 * 用户登录和退出请求
 *
 * @author wpfei
 */

@Controller
@RequestMapping("/auth")
public class LoginController {
    protected static Logger logger = LoggerFactory.getLogger(LoginController.class);
    // ========================================================================
    private final static int USERTYPE = 1;
    // 注入userManger类
    @Autowired
    UserManager userManager;

    // ===============================================================================================================
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    // 用户登录
    public JSONObject login(@RequestBody String jsonObj, HttpServletRequest request, HttpSession httpSession)
            throws JSONException {
        logger.info("ENTER APP USER LOGIN METHOD");
        UsernamePasswordToken AppToken = null;
        ConsoleUser consoleUser = null;
        JSONObject resultJSONObject = new JSONObject();
        resultJSONObject.put("success", true);
        String errorMessage = "";
        boolean isAuth = false;
        logger.debug("httpSession session id: " + httpSession.getId().toString());
        org.json.JSONObject jsonObject2 = new org.json.JSONObject(jsonObj);
        String userName = jsonObject2.getString("username");
        String password = jsonObject2.getString("password");
        logger.debug("USERNAME" + userName + ";PASSWORD" + password);
        logger.info("loginName:" + userName + ";loginPassword:" + password);
        if (userName != null && password != null) {
            AppToken = new UsernamePasswordToken(userName, password);
        } else {
            resultJSONObject.put("message", "请输入账号密码重新登录");
        }

        try {
            //设置用户类型为1 表示后台用户，方便认证和授权
            userManager.setUSERTYPE(USERTYPE);
            Subject user = SecurityUtils.getSubject();
            Session session = user.getSession();
            //调用subject 的login方法进行认证，自动传递到securityManager，再传递到Realm进行认证
            //认证失败通过抛出异常来处理
            user.login(AppToken);
            consoleUser = userManager.loadConUserByName(userName);
            String userID = (String) user.getPrincipal();
            logger.debug("username: " + userID);
            logger.debug("session id: " + session.getId().toString());
            logger.info("User [" + userID + "] logged in successfully.");
            logger.info("User is authenticated:  " + user.isAuthenticated());
            session.setAttribute("USERNAME", userID);
            isAuth = user.isAuthenticated();
            httpSession.setAttribute("user", user);
        } catch (UnknownAccountException uae) {
            errorMessage = "用户认证失败：" + "username wasn't in the system.";
            logger.info(errorMessage);
        } catch (IncorrectCredentialsException ice) {
            errorMessage = "用户认证失败：" + "password didn't match.";
            logger.info(errorMessage);
        } catch (LockedAccountException lae) {
            errorMessage = "用户认证失败：" + "account for that username is locked - can't login.";
            logger.info(errorMessage);
        } catch (AuthenticationException e) {
            errorMessage = "登录失败错误信息：" + e;
            logger.error(errorMessage);
            e.printStackTrace();
            AppToken.clear();
        } finally {
            if (isAuth) {
                if (consoleUser.getState().equals(Constants.USER_UNLCK)) {
                    AppToken.setRememberMe(true);
                    httpSession.setAttribute("conuser", consoleUser);
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("logIn", true);
                    jsonObject3.put("userInfo", consoleUser);
                    resultJSONObject.put("data", jsonObject3);
                } else {
                    resultJSONObject.put("ErrorMessage", "该用户被锁定");
                    JSONObject jsonObject3 = new JSONObject();
                    jsonObject3.put("logIn", false);
                    jsonObject3.put("userInfo", null);
                    resultJSONObject.put("data", jsonObject3);
                    errorMessage = "用户登录失败：" + "该用户被锁定";
                    logger.info(errorMessage);

                }
            } else

            {
                resultJSONObject.put("ErrorMessage", errorMessage);
                JSONObject jsonObject3 = new JSONObject();
                jsonObject3.put("logIn", false);
                jsonObject3.put("userInfo", null);
                resultJSONObject.put("data", jsonObject3);
                errorMessage = "用户认证失败：" + "账户未认证成功";
                logger.info(errorMessage);
            }
            //Assert.assertTrue(true,);
            return resultJSONObject;
        }

    }

    // ==================================================================================================================

    /**
     * 退出APP
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public Object getDeniedPage() {
        logger.info("ENTER APP USER TO LOGOUT");
        Subject user = SecurityUtils.getSubject();
        logger.info(user.toString());
        user.logout();
        logger.info("USER LOGOUT SUCCESS");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", true);
        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("logIn", false);
        jsonObject3.put("userInfo", null);
        jsonObject.put("data", jsonObject3);
        return jsonObject;
    }
}